import {projectFlagTreeList, projectList, projectTreeList} from "./project_data.js";
//
console.log("projectList", projectList)
const Main = {
    data() {
        return {
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            projectFlagTreeList: projectFlagTreeList,
            cmdRadioMap: {//使用``包裹的字段是需要替换成活的字段
                git: ["pwd", "git branch", "git log -n 3"],
                build_upload_dev: ["pwd", "npm run build:pro", "rm -rf dist.zip", "zip -r dist.zip dist",
                    "upload.sh 8.130.43.148 /www/`curProjectName`",
                    "open -a \"Google Chrome\" `devPath`"],
                build_upload_test: ["pwd", "npm run build:pro", "rm -rf dist.zip", "zip -r dist.zip dist",
                    "upload.sh 43.132.131.88 /www/`curProjectName`",
                    "open -a \"Google Chrome\" `testPath`"],
            },
            exchangeMap: {//需要替换成活的字段的对象
                curProjectName: "",
                devPath: "",
                testPath: "",
            },
            showModelRadioValue: "line",
            selModelRadioValue: "single",
            projectList: projectList,
            treeData: projectTreeList,
            filterText: '',//搜索文本
            selProjectFlagList: [],//选择的项目标签数组
            checkNodeList: [],//选中的node节点数组
            currentNodeItem: {},//当前选中的node数据
            customCmdText: "",
            cmdRadioValue: "git",//git build_upload
        };
    },
    watch: {
        //根据搜索文本条件执行树的筛选
        filterText(val) {
            if (this.showModelRadioValue === "tree") this.$refs.tree2.filter(val);
        },
        //根据标签过滤条件执行树的筛选
        selProjectFlagVal(val) {
            if (this.showModelRadioValue === "tree") this.$refs.tree2.filter(val);
        }
    },
    computed: {
        filterProjectList() {
            return this.projectList.filter(project => {
                if (this.filterText) return project.id.toLocaleLowerCase().indexOf(this.filterText.toLocaleLowerCase()) > -1;
                else if (this.selProjectFlagVal) return project.flag.includes(this.selProjectFlagVal)
                return true
            })
        },
        //清空选择按钮是否可用
        canClearSelectUse() {
            return this.checkNodeList.length
        },
        //打开项目按钮是否可用
        canOpenProject() {

        },
        //打开文件夹按钮是否可用
        canOpenFileDirPath() {

        },
        canRunCustomCmdUse() {
            let deployList = ["build_upload_dev", "build_upload_test"]
            if (deployList.includes(this.cmdRadioValue)) return this.currentNodeItem.devPath
            else return this.currentNodeItem.id
        },
        selProjectFlagVal() {
            let flagListLength = this.selProjectFlagList.length
            return flagListLength && this.selProjectFlagList[flagListLength - 1] || ""
        }
    },
    mounted() {
        console.log("projectList====", JSON.stringify(this.projectList))
    },
    methods: {
        //项目的标签改变时
        projectFlagChange(val) {
            console.log(val)
        },
        //过滤tree的数据
        filterNode(value, project) {
            if (this.filterText) return project.id.toLocaleLowerCase().indexOf(this.filterText.toLocaleLowerCase()) > -1;
            else if (this.selProjectFlagVal) return project.flag.includes(this.selProjectFlagVal)
            return true;
        },
        //选择radio事件
        radioChange(val) {
            if (val === "tree") {
                this.$nextTick(() => {
                    this.$refs.tree2.filter();
                    this.$refs.tree2.setCheckedKeys(this.checkNodeList.map(item => item.id));
                })
            }
        },
        //tree选择事件
        //在切换选择项的时候，新选择的和之前撤销选择的都会进来【这里是最麻烦的】。这里只判断最新的是新选择的，或者最新选择的和之前的一样的。
        handleCheckChange(data, checked, indeterminate) {
            if (checked) this.selectProjectItem(data)
            else if (data.id === this.currentNodeItem.id && this.checkNodeList.length) this.selectProjectItem(data)
            //上面判断this.checkNodeList.length是区分是否点的清空按钮触发的。
        },
        //关闭选择的tag事件
        handleClose(node) {
            this.selectProjectItem(node)
        },
        //选择项目
        selectProjectItem(node) {
            console.log("node.id=====", node.id)
            this.projectList = this.projectList.map(item => {
                if (item.id === node.id) item.selected = !item.selected
                else if (this.selModelRadioValue === "single") item.selected = false
                return item
            })
            this.checkNodeList = this.projectList.filter(item => item.selected)
            //如果显示是树模式，并且选择的节点和之前的节点不一致就 手动设置树选择的数据
            if (this.showModelRadioValue === "tree" && this.currentNodeItem.id && this.currentNodeItem.id !== node.id) {
                this.$refs.tree2.setCheckedKeys(this.checkNodeList.map(item => item.id));
            }
            this.genExchangeMapData()
            this.cmdRadioChange(this.cmdRadioValue)
        },
        //生成替换对象的数据
        genExchangeMapData() {
            this.currentNodeItem = this.checkNodeList.length && this.checkNodeList[0] || {}
            this.exchangeMap.curProjectName = this.currentNodeItem.label
            this.exchangeMap.devPath = this.currentNodeItem.devPath
            this.exchangeMap.testPath = this.currentNodeItem.testPath
        },
        //清空选择的节点
        clearSelectNode() {
            this.projectList = this.projectList.map(item => {
                item.selected = false
                return item
            })
            this.checkNodeList = []
            this.currentNodeItem = {}
            this.$refs.tree2.setCheckedKeys([]);
        },
        //获取节点的绝对路径
        getNodeAbsolutePath(node) {
            let basePath = '/Users/zhaoyj/'
            let nodePath = node.id.replace(/,/g, "/")
            return `${basePath}${nodePath}`
        },
        //显示/隐藏自定义命令输入框
        showCustomCmd() {
            let displayStyle = document.getElementById("customCmdInputLayout").style.display;
            document.getElementById("customCmdInputLayout").style.display = displayStyle === "flex" ? "none" : "flex";
            this.cmdRadioChange(this.cmdRadioValue)
        },
        //获取需要替换字段的活数据的字段
        exchangeMapByLiveData(str) {
            console.log("this.exchangeMap", this.exchangeMap)
            let replaceStr = str.split("`").filter(item => item).map(item => {
                if (this.exchangeMap.hasOwnProperty(item)) item = this.exchangeMap[item]
                return item
            }).join("")
            return replaceStr
        },
        //自定义命令选择事件
        cmdRadioChange(val) {
            let cmdList = this.cmdRadioMap[val]
            //在数组最前面添加一个cd命令
            if (this.checkNodeList.length) {
                //将自定义命令数组中的替换字段 使用exchangeMap的活数据替换了。
                cmdList = cmdList.map(item => {
                    if (item.indexOf("`") !== -1) {
                        item = this.exchangeMapByLiveData(item)
                    }
                    return item
                })
                cmdList = [`cd ${this.getNodeAbsolutePath(this.currentNodeItem)}`, ...cmdList]
            }
            this.customCmdText = cmdList.join("\n")
        },
        //清除日志按钮
        clearLog() {
            let sseResView = document.getElementById("sseResView")
            sseResView.innerHTML = ""
        },
        //打开项目
        openProject() {
            let openFileCmdList = this.checkNodeList.map(item => {
                let basePath = '/Users/zhaoyj/'
                let nodePath = item.id.replace(/,/g, "/")
                return `webstorm ${basePath}/${nodePath}`
            })
            this.runCommandRequest(openFileCmdList)
        },
        //打开文件夹
        openFileDir() {
            let openFileCmdList = this.checkNodeList.map(item => {
                return `open ${this.getNodeAbsolutePath(item)}`
            })
            this.runCommandRequest(openFileCmdList)
        },
        //执行自定义命令
        runCustomCmd() {
            let customCmdList = this.customCmdText.split("\n").filter(item => item)
            this.runCommandRequest(customCmdList)
        },
        //执行命令行
        runCommandRequest(commandList) {
            let sseResView = document.getElementById("sseResView")
            let codeLayout = document.getElementById("codeLayout")
            let emptyLine = `<p style="color:blue">========================================================================</p>`
            sseResView.innerHTML = sseResView.innerHTML + emptyLine
            const eventSource = new EventSource(`/runCmd?commandList=${encodeURIComponent(JSON.stringify(commandList))}`);
            //消息监听
            eventSource.onmessage = (event) => {
                console.log("EventSource===onmessage传入消息", event.data)
                if (event.data === 'end') {
                    eventSource.close()
                } else {
                    let color = event.data && event.data.indexOf("####") === -1 ? "black" : "#00CD7F"
                    let fontSize = event.data && event.data.indexOf("####") === -1 ? "12px" : "13px"
                    let codeLine = `<p style="color:${color};font-size:${fontSize}">${event.data}</p>`
                    sseResView.innerHTML = sseResView.innerHTML + codeLine
                    codeLayout.scrollTop = codeLayout.scrollHeight
                }
            };
            //连接成功
            eventSource.onopen = function (event) {
                console.log('EventSource===onopen连接打开')
            }
            //连接出错
            eventSource.onerror = function (error) {
                if (eventSource.readyState === EventSource.CLOSED) {
                    // 连接已关闭，可能需要重新连接
                    console.error('EventSource===onerror连接断掉了:', error);
                }
            }
        }
    }
};

const Ctor = Vue.extend(Main)
new Ctor().$mount('#app')